package com.yanqu.road.server.manger;

import com.yanqu.road.dao.impl.player.ChatControlDaoImpl;
import com.yanqu.road.entity.message.BanChatUserData;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatControlMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(ChatControlMgr.class.getName());
    //userid messageType
    private static Map<Long, Map<Integer, BanChatUserData>> banChatUserDataMap = new ConcurrentHashMap<>();


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean reloadData() {
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    public static void reloadChatControl(int channelId) {
        long nowTime = DateHelper.getCurrentSecond();
        List<BanChatUserData> tempList = new ChatControlDaoImpl().getBanChatUserDataMap(channelId);
        Map<Long, Map<Integer, BanChatUserData>> tempDataMap = new ConcurrentHashMap<>();
        for (BanChatUserData chatUserData : tempList) {
            if (StringUtils.isNullOrEmpty(chatUserData.getHiddenTimeParam()) && nowTime > chatUserData.getSilenceEndTime()) {
                //没有被禁言和静默的玩家不读进来
                continue;
            }
            Map<Integer, BanChatUserData> typeMap = tempDataMap.get(chatUserData.getUserId());
            if (null == typeMap){
                typeMap = new ConcurrentHashMap<>();
                tempDataMap.put(chatUserData.getUserId(), typeMap);
            }
            typeMap.put(chatUserData.getMessageType(), chatUserData);
        }
        synchronized (banChatUserDataMap){
            banChatUserDataMap = tempDataMap;
        }
    }

    public static List<BanChatUserData> getBanChatUserList() {
        synchronized (banChatUserDataMap){
            List<BanChatUserData> list = new ArrayList<>();
            for (Map<Integer, BanChatUserData> dataMap : banChatUserDataMap.values()) {
                list.addAll(dataMap.values());
            }
            return list;
        }
    }

    public static Map<Long, Map<Integer, BanChatUserData>> getBanChatUserDataMap() {
        return banChatUserDataMap;
    }
}
